<?php


define("TOKEN","echo_server");

function checkSignature(){

    $signature =$_GET['signature'];
    $nonce =$_GET['nonce'];
    $timestamp=$_GET['timestamp'];


    $tmpArr = array($nonce,$timestamp,TOKEN);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1( $tmpStr );
    if( $tmpStr == $signature ){
        return true;
    }
    return false;

}
function e_log($log){
    file_put_contents("log.txt",$log,FILE_APPEND);
    }
    
function mainpageurl($s){
    if($s == '主页'){
        return '<a href="http://czz2x.xyz">点击进入主页：czz2x.xyz</a>';
    }else{
        return $s;
    }
}
   
function getPostData(){
    $data =$GLOBALS['HTTP_RAW_POST_DATA'];
    return $data;
}

function doCurlGetRequest($url,$data,$timeout = 5){
    if ($url==''|| $timeout <=0){
        return false;
    }
    $url = $url.'?'.http_build_query($data);
    
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($con, CURLOPT_TIMEOUT, false);
    
    return curl_exec($con);
}

if (false == checkSignature()){
    exit(0);
}
$echostr=$_GET['echostr'];
if($echostr){
    echo $echostr;
    exit(0);
}


$PostData = getPostData();
if(!$PostData){
    e_log('null  ');
    echo "wrong input!";
    exit(0);
    }
    
$xmlObj=simplexml_load_string($PostData,'SimpleXMLElement',LIBXML_NOCDATA);
if(!$xmlObj){
    echo "wrong input!";
    exit(0);
    }
$fromUserName=$xmlObj->FromUserName;
$toUserName=$xmlObj->ToUserName;
$msgType=$xmlObj->MsgType;

if('text' != $msgType){
    $retMsg='只支持文本消息';
}else{
    $content =$xmlObj->Content;
    $retMsg=mainpageurl($content);
}
$retTmp ="
	 <xml>
 <ToUserName><![CDATA[%s]]></ToUserName>
 <FromUserName><![CDATA[%s]]></FromUserName>
 <CreateTime>%s</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[%s]]></Content>
<FuncFlag>0</Funcflag>
 </xml>";
$resultStr=sprintf($retTmp,$fromUserName,$toUserName,time(),$retMsg);
echo $resultStr;
e_log($fromUserName);


?>